<?php

namespace App\Console\Commands;

use App\Models\Bus\BusDistribution;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Storage;

class syncMileageData extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'sync:mileage';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '同步里程数据';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return void
     */
    public function handle(): void
    {
        $startDay = date('Y-m-d', strtotime('-1 month'));
        $lastDay = date('Y-m-d', strtotime('-1 day'));
        $dates = getListFromDateRange($startDay, $lastDay);

        Storage::append('SyncMileage.log', '########## '.date('Y-m-d H:i:s').' ##########');

        // 同步数据
        foreach ($dates as $k => $date) {
            $this->updateOrInsertSignData($date);
            sleep(12);
        }

        Storage::append('SyncMileage.log', PHP_EOL);
    }

    public function updateOrInsertSignData($date): void
    {
        $this->info('- '.$date);
        $lines = BusDistribution::query()->where('line', '!=', '0')->groupBy('line')->pluck('line')->toArray();

        $sign = Http::get('http://117.34.118.31:8101/api/bus/mileage/list', [
            'date' => $date,
        ]);
        $data = $sign->json();
        $code = $data['code'];
        if ($code === 200) {
            $insertData = [];
            foreach ($data['data'] as $v) {
                if (in_array((int) $v['lineName'], $lines, true) && (string) $v['orgName'] === '安康公共交通有限责任公司') {
                    $insertData[] = [
                        'date'                  => $date,
                        'line'                  => $v['lineName'],
                        'license_plate_num'     => str_replace('陕G', '', $v['busNum']),
                        'self_numbering'        => $v['busCode'],
                        'plan_times'            => $v['planTrip'],
                        'actual_times'          => $v['runTrip'],
                        'departure_rate'        => $v['rate'],
                        'operating_mileage'     => $v['runMileage'],
                        'non-operating_mileage' => $v['nonMileage'],
                        'gps_mileage'           => $v['totalMileage'],
                        'plan_mileage'          => $v['planMileage'],
                        'rated_mileage'         => $v['ratedMileage'],
                        'created_at'            => date('Y-m-d H:i:s'),
                    ];
                }
            }
            // 先删除数据，再插入
            DB::table('akbus_mileage')->where('date', $date)->delete();
            $result = DB::table('akbus_mileage')->insert($insertData);
            if ($result) {
                $this->info('- Insert Success'.PHP_EOL);
                Storage::append('SyncMileage.log', 'Date: '.$date.', Result: Insert Success');
            } else {
                $this->info('- Insert Failure'.PHP_EOL);
                Storage::append('SyncMileage.log', 'Date: '.$date.', Result: Insert Failure');
            }
        } else {
            $this->info('- Get Failure Code: '.$code.' Msg: '.$data['msg'].PHP_EOL);
            Storage::append('SyncMileage.log', 'Date: '.$date.', Result: Get Failure, Code: '.$code.', Msg: '.$data['msg']);
        }
    }
}
